#!/usr/bin/env python
#-*-coding:utf-8-*-
# ---------------------------------
# version:  1.0
#
# create-time:      <2008/12/03 02:52:08>
# last-update-time: <halida 12/20/2008 23:03:19>
# ---------------------------------
# module : entity view

from qtlib import *
from datetime import *

import entity,loop

ENTITY_CHANGED = "entityChanged"

class EntityView(QWidget):
    """show and update one entity."""
    def __init__(self,pool):
        QWidget.__init__(self)
        self.pool=pool
        self.entity=None
        #component
        self.name = QLineEdit()
        self.desc = QTextEdit()
        self.tags = QLineEdit()

        self.scheduled = QCheckBox("scheduled?")
        self.nextTime = QDateTimeEdit()

        self.tomorrowButton = QPushButton("delay to tomorrow")
        self.scheduleToDayButton = QPushButton("schedule to day")

        self.scheduleTime = QComboBox()
        for i in range(0,23):
            self.scheduleTime.addItem(str(i))

        self.looped = QCheckBox("looped?")
        self.loopButton = QPushButton("set loop")

        self.lastTime = QDateTimeEdit()

        self.data = QTextEdit()

        self.saveButton = QPushButton("&save")
        #layout
        self.setLayout()
        #event
        self.setEvent()

    def setEvent(self):
        conn(self.pool,entity.POOL_CHANGED,self.refresh)

        conn(self.name,"editingFinished()",self.needSave)
        conn(self.desc,"textChanged()",self.needSave)
        conn(self.tags,"editingFinished()",self.needSave)
        conn(self.nextTime,"dateTimeChanged(const QDateTime &)",self.needSave)
        conn(self.scheduled,"stateChanged ( int )",self.needSave)
        conn(self.looped,"stateChanged ( int )",self.needSave)
        conn(self.lastTime,"dateTimeChanged(const QDateTime &)",self.needSave)

        conn(self.saveButton,"clicked(bool)",self.setEntity)
        conn(self.tomorrowButton,"clicked(bool)",self.scheduleToTomorrow)
        conn(self.scheduleToDayButton,"clicked(bool)",self.scheduleToDay)
        conn(self.scheduleTime,"currentIndexChanged (int)",self.scheduleToTime)
        conn(self.loopButton,"clicked(bool)",self.setLoop)

    def setLayout(self):
        #layout
        self.layout = QVBoxLayout(self)

        self.tab = QTabWidget()
        #main tab
        self.tab1 = QWidget()
        l = QVBoxLayout(self.tab1)
        l.addWidget(self.name)
        l.addWidget(self.desc)
        l.addWidget(self.tags)
        #schedule tab
        self.tabTime = QWidget()
        l = QGridLayout(self.tabTime)
        l.addWidget(self.scheduled,0,0)
        l.addWidget(self.nextTime,0,1)

        l.addWidget(self.tomorrowButton,1,0)
        l.addWidget(self.scheduleToDayButton,1,1)

        l.addWidget(QLabel("schedule To Time:"),2,0)
        l.addWidget(self.scheduleTime,2,1)

        l.addWidget(self.looped,3,0)
        l.addWidget(self.loopButton,3,1)

        l.addWidget(QLabel("Loop Last Time:"),4,0)
        l.addWidget(self.lastTime,4,1)

        l.setRowStretch(5,1)

        self.tab.addTab(self.tab1,"main")
        self.tab.addTab(self.tabTime,"schedule")
        self.tab.addTab(self.data,"data")

        self.buttonLayout = QHBoxLayout()
        self.buttonLayout.addStretch(1)
        self.buttonLayout.addWidget(self.saveButton)

        self.layout.addWidget(self.tab)
        self.layout.addLayout(self.buttonLayout)

    #---save and load---
    def entityValid(self):
        return self.entity

    def getEntity(self,id):
        self.entity = self.pool.get(id)
        self.refresh()

    def refresh(self,id=None):
        #check if this entity need refresh
        if not self.entityValid():
            self.setSave(False)
            return
        if id!=None:
            if id != self.entity.id:
                return
        self.tab.setCurrentIndex(0)
        #get data
        self.name.setText(self.entity.name)
        self.desc.setPlainText(self.entity.desc)
        self.tags.setText(",".join(
                list(self.entity.tags)))
        self.data.setText(self.entity.data())
        self.nextTime.setDateTime(self.entity.nextTime)
        self.lastTime.setDateTime(self.entity.lastTime)
        self.scheduled.setChecked(self.entity.scheduled)
        self.looped.setChecked(self.entity.looped)
        self.setSave(False)

    def setEntity(self):
        if not self.entityValid():return
        logging.info("seting entity:%s",unicode(self.entity.name))
        self.pool.set(self.entity.id,
                      name=unicode(self.name.text()),
                      desc=unicode(self.desc.toPlainText()),
                      tags=set(unicode(self.tags.text()).split(",")),
                      nextTime=toDatetime(self.nextTime.dateTime()),
                      lastTime=toDatetime(self.lastTime.dateTime()),
                      scheduled=self.scheduled.isChecked(),
                      looped=self.looped.isChecked()  
                      )
        self.changed()

    def changed(self):
        emit(self,ENTITY_CHANGED,self.entity.id)

    #---update---
    def setSave(self,enabled):
        self.saveButton.setEnabled(enabled)        

    def needSave(self):
        self.setSave(True)

    def cleanUp(self):
        self.entity=None
        for obj in self.__dict__:
            try:
                obj.clear()
            except:
                pass

    #---schedule---
    def scheduleTo(self,totime):
        if not self.entityValid():return
        self.entity.addTag(entity.LATER)
        self.pool.set(self.entity.id,
                      nextTime=totime,
                      scheduled=True)
        self.changed()

    def schedule(self):
        if not self.entityValid():return
        #get time
        scheduleTime = self.nextTime.dateTime()
        #set
        self.scheduleTo(scheduleTime)

    def scheduleToDay(self):
        if not self.entityValid():return
        #get a day
        nextDay = getDay(self)
        if nextDay == None:return
        #set
        self.scheduleTo(nextDay)

    def scheduleToTomorrow(self):
        if not self.entityValid():return
        #get tomorrow
        tomorrow = datetime.today() + timedelta(days=1)
        year = tomorrow.year
        month = tomorrow.month
        day = tomorrow.day
        #get the beginning of tomorrow
        tomorrowStart = datetime(year,month,day)
        logging.debug(tomorrowStart)
        #set
        self.scheduleTo(tomorrowStart)

    def scheduleToTime(self,hour):
        if not self.entityValid():return
        #first schedule day,then schedule time
        if not self.entity.scheduled:
            day = datetime.today()
        else:
            day = entity.nextTime
        newTime = datetime(day.year,
                           day.month,
                           day.day,
                           hour)
        logging.debug("schedule to time: %s",str(newTime))
        self.scheduleTo(newTime)

    #---loop---
    def setLoop(self):
        ok,loopCondition = loop.editLoop(self,
                                         self.entity.loopCondition)
        if not ok:return
        #set
        self.pool.set(self.entity.id,
                      looped = True,
                      loopCondition=loopCondition)
        self.changed()
